
//
//  YQInvitationVC.m
//  NewRetail
//
//  Created by yuqin on 2019/7/11.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQInvitationVC.h"
#import "YQInvitationView.h"
#import <Photos/Photos.h>

@interface YQInvitationVC ()

@property (nonatomic, strong) YQInvitationView *backView;
@property (nonatomic, strong) UIImageView *backImgView;
@property (nonatomic, strong) UIImageView *codeImg;
@property (nonatomic, strong) UILabel *desLabOne;
@property (nonatomic, strong) UIImageView *desImgView;

@end

@implementation YQInvitationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.backView];
    [self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [self.backView addSubview:self.backImgView];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headView.mas_bottom).mas_equalTo(FIT(50));
        make.centerX.mas_equalTo(self.backView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(FIT(295), FIT(295)));
    }];
    
    [self.backImgView addSubview:self.codeImg];
    [self.codeImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.backImgView.mas_centerX);
        make.centerY.mas_equalTo(self.backImgView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(FIT(257), FIT(257)));
    }];
    NSString *codeStr = [YQPersonInformationModel sharedYQPersonInformationModel].referralCode;
    self.codeImg.image=[self createNonInterpolatedUIImageFormCIImage:[self creatQRcodeWithUrlstring:[NSString stringWithFormat:@"http://192.168.1.55:8952/share?code=%@",codeStr]] withSize:FIT(257)];
    
    [self.backView addSubview:self.desLabOne];
    [self.backView addSubview:self.desImgView];
    
    [self.desLabOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(self.backImgView.mas_bottom).mas_equalTo(FIT(15));
        make.height.mas_equalTo(FIT(15));
    }];
    
    [self.desImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.desLabOne.mas_bottom).mas_equalTo(FIT(54));
        make.centerX.mas_equalTo(self.backView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(FIT(234), FIT(154)));
    }];
    
}

- (YQInvitationView *)backView {
    if (!_backView) {
        _backView = [[YQInvitationView alloc] init];
        //长按复制二维码
        UILongPressGestureRecognizer *LongPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
        [_backView addGestureRecognizer:LongPressGesture];
        WeakSelf(self);
        _backView.BackBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
    }
    return _backView;
}

- (UIImageView *)backImgView {
    if (!_backImgView) {
        _backImgView = [YQViewFactory imageViewWithImage:YQ_IMAGE(@"code_back")];
        _backImgView.contentMode = UIViewContentModeScaleToFill;
    }
    return _backImgView;
}

- (UIImageView *)codeImg {
    if (!_codeImg) {
        _codeImg = [YQViewFactory imageViewWithImage:YQ_IMAGE(@"")];
        _codeImg.contentMode = UIViewContentModeScaleToFill;
    }
    return _codeImg;
}

- (UILabel *)desLabOne {
    if (!_desLabOne) {
        _desLabOne = [YQViewFactory labelWithTextColor:WhiteColor textAlignment:NSTextAlignmentCenter fontSize:FIT(15) userBold:NO];
        _desLabOne.text = @"长按保存二维码";
    }
    return _desLabOne;
}

- (UIImageView *)desImgView {
    if (!_desImgView) {
        _desImgView = [YQViewFactory imageViewWithImage:YQ_IMAGE(@"des_back")];
        _desImgView.contentMode = UIViewContentModeScaleToFill;
    }
    return _desImgView;
}

- (CIImage *)creatQRcodeWithUrlstring:(NSString *)urlString{
    
    // 1.实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
    [filter setDefaults];
    // 3.将字符串转换成NSdata
    NSData *data  = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
    [filter setValue:data forKey:@"inputMessage"];
    // 5.生成二维码
    CIImage *outputImage = [filter outputImage];
    return outputImage;
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    //长按截图
    if (longPress.state == UIGestureRecognizerStateEnded) {
        UIImage *screenshots = [self nomalSnapshotImage];
        [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
            //在上传之前判断本地是否有改图片
            
            [PHAssetChangeRequest creationRequestForAssetFromImage:screenshots];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            NSString *msg = nil;
            if (error) {
                msg = @"保存图片失败" ;
            } else {
                msg = @"保存图片成功" ;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [LCProgressHUD showMessage:msg];
            });
        }];
    }
    
    
}

- (UIImage *)nomalSnapshotImage
{
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, [UIScreen mainScreen].scale);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

@end
